// <script type="text/javascript">

// 所有分类数据
var categories = <?=JSON::encode($categories, TRUE)?>;

// 分类索引
var category_maps = [];

// 构造索引
for (var i=0; i<categories.length; i++) {
    category_maps[categories[i].cat_id] = {is_parent : categories[i].is_parent, path : categories[i].path, parent_id : categories[i].parent_id};
}

/**
 * 逆向递归创建下拉框
 */
function category_select_reverse(sel_id, ele_name, callback) {
    var wrap = $('<span></span>');

    // 递归创建
    function _create(parent_id, sel_id) {
        wrap.prepend(category_select_create(parent_id, ele_name, callback, sel_id));
        if (parent_id > 0) {
            _create(category_maps[parent_id].parent_id, parent_id);
        }
    }

    _create((sel_id == 0) ? 0 : category_maps[sel_id].parent_id, sel_id);

    if (sel_id > 0 && category_maps[sel_id].is_parent == 1) {
        // 创建子下拉框
        wrap.append(category_select_create(sel_id, ele_name, callback));
    }

    return wrap;
}

/**
 * 创建分类下拉选框
 */
function category_select_create(parent_id, ele_name, callback, sel_id) {

    var ele = $('<select name="' + ele_name + '" style="margin-right:2px;"><option value="' + parent_id + '"></option></select>');

    // 绑定事件
    ele.change(function(){
        $(this).nextAll().remove();
        if (parent_id == 0 || this.value != parent_id) {
            category_select_change(this, callback);
        }
    });

    // 生成下拉选项
    for (var i=0; i<categories.length; i++) {
        if (categories[i].parent_id == parent_id) {
            var prefix = (categories[i].is_parent == '1') ? '+ ' : '- ';
            var selected = (sel_id==categories[i].cat_id) ? ' selected' : '';
            ele.append('<option value="' + categories[i].cat_id + '"' + selected + '>' + prefix + categories[i].name + '</option>');
        }
    }

    return ele;
}

/**
 * 分类下拉选框值发生变化
 */
function category_select_change(obj, callback) {

    var ret = true;

    // callback
    if (typeof callback == 'function') {
        ret = callback(obj, category_maps[obj.value]);
    }

    // append childs
    if (ret && obj.value > 0 && category_maps[obj.value].is_parent == 1) {
        $(obj).after(category_select_create(obj.value, $(obj).attr('name'), callback));
    }

    return ret;
}
// </script>